package com.atguigu.gulimall.seckill.interceptor;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.vo.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberRespVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        //匹配上 kill 才拦截，
        boolean match = antPathMatcher.match("/kill", uri);
        if(match){

            //登陆之后从session中拿到LOGIN_USER的信息
            MemberRespVo attribute = (MemberRespVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);

            //thread+static共享出去，因为是微服务，每个服务要拿自己的，服务之间不能共享登陆账户的信息
            //要单独拿到，只有session在各个服务之间是共享的
            if (attribute != null) {
                //登陆了将loginUser在 controller -》 service -》 impl 之间共享
                //使用static+threadLoacl 共享出去
                loginUser.set(attribute);
                return true;

            }else{

                //没登陆 拦截，跳去登陆页面
                request.getSession().setAttribute("msg","请先去登陆");
                response.sendRedirect("http://auth.gulimall.com/login.html");
                return false;

           }
        }
        return true;
    }
}
